package com.cjzuji.rental.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.cjzuji.rental.dao.*;
import com.cjzuji.rental.mapper.OrderBillMapper;
import com.cjzuji.rental.mapper.OrderMapper;
import com.cjzuji.rental.pojo.OrderBill;
import com.cjzuji.rental.pojo.Orders;
import com.cjzuji.rental.service.YouPinService;
import com.cjzuji.rental.service.YpRiskService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class AiDSaveServiceImpl {
    @Autowired
    OrderMapper orderMapper;
    @Autowired
    OrderBillMapper orderBillMapper;
    @Autowired
    AiDouOrderDao aiDouOrderDao;
    @Autowired
    AiDouUserDao aiDouUserDao ;
    @Autowired
    AiDouContractDao aiDouContractDao;
    @Autowired
    AiDouBillDao aiDouBillDao;
    @Autowired
    YouPinService youPinService;

    private static final Logger logger = LoggerFactory.getLogger(AiDSaveServiceImpl.class);
    //抽离保存save
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void getListSave(String orderId, Map<String, Object> item,Map<String,Object> orderDetail,
                            List<Map<String, Object>> orderBillList) {
        try {
            Double outBuyAmount = 0.0;
            if (orderBillList.size()> 0){
                Map<String, Object> lastBill = orderBillList.get(orderBillList.size()-1);
                outBuyAmount = Double.parseDouble(lastBill.get("allinAmount").toString()) ;
            }
            // 判断 当前的订单号是否在数据库中存在
            QueryWrapper<Orders> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("order_id",orderId);
            List<Orders> existingOrder = orderMapper.selectList(queryWrapper);
            logger.info("existingOrder {}",existingOrder);
            if (existingOrder.size() > 0 ) {
                logger.info("订单已存在，对订单进行更新");
                //更新订单状态，快递单号
                Orders existing = existingOrder.get(0);
                updateExistingOrder(existing,item,orderDetail);
            }
            else{
                System.out.println("进去开始保存order~~~~~~~~~~~~~~"+orderId);
                Long orderID = aiDouOrderDao.save(item,orderDetail,outBuyAmount);
                System.out.println("进去开始保存user~~~~~~~~~~~~~~"+orderID);
                aiDouUserDao.save(item,orderDetail,orderID);
//                //调用风控审批接口
//                String riskApp = youPinService.riskApproval(existingOrder.get(0),orderId);
//                logger.info("风控审批接口完成，返回creditId {}",riskApp);
//                //调用风控查询接口
//                youPinService.queryApproval(riskApp);
                if (orderDetail.get("rzzlUrl") != null && orderDetail.containsKey("rzzlUrl")){
                    System.out.println("进去开始保存contract~~~~~~~~~~~~~~"+orderID);
                    aiDouContractDao.save(orderDetail,orderID);
                    if (orderBillList != null && orderBillList.size() > 0){
                        //账单list
                        System.out.println("进去开始保存bill~~~~~~~~~~~~~~"+orderID);
                        aiDouBillDao.save(orderBillList, orderID);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }

    //租用中更新账单和合同
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
    public void getzySave(String orderId, Map<String, Object> item,Map<String,Object> orderDetail,List<Map<String,Object>> orderBillList) {
        try {
            // 当前的订单号是否在数据库中存在 如果存在  跳出当前循环
            QueryWrapper<OrderBill> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("orders_id",orderId);
            List<OrderBill> existingBill = orderBillMapper.selectList(queryWrapper);
            logger.info("查询到的已存在账单数量: {}",existingBill.size());
            // 订单已存在
            if (!existingBill.isEmpty() ) {
                Long orderID = existingBill.get(0).getOrderId();
                // 订单已存在，对比两方的“还款状态”数据，如果相同不变，不同对数据库账单表进行更新
                logger.info("订单已存在~~,对比更新数据",orderId);
                compareUpdate(orderBillList,existingBill,orderID);
            }
            else{
                //更新orders表中的分配人，押金，订单状态，碎屏险，碎屏险状态，快递单号，订单更新时间
                int screenRisksType = 0;
                if(Double.parseDouble(orderDetail.get("screenInsure").toString()) > 0){
                    screenRisksType = 1;
                }
                Double surplusBondAmt = 0.0;
                if (orderDetail.get("secondDeposit") != null){
                    surplusBondAmt = Double.parseDouble(orderDetail.get("secondDeposit").toString());
                }
                UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
                updateWrapper.eq("order_id",orderId)
                        .set("assigner", item.get("riskManNickName").toString())   //分配人
                        .set("surplus_bond_amt",surplusBondAmt)  //押金
                        .set("status",3)     //订单状态
                        .set("screen_risks_amount",Double.parseDouble(orderDetail.get("screenInsure").toString()))  //碎屏险
                        .set("screen_risks_type",screenRisksType)   //碎屏险状态
                        .set("delivery_no",orderDetail.get("logisticsNo").toString())   //快递单号
                        .set("update_time",new Date());   //订单更新时间
                orderMapper.update(updateWrapper);
                logger.info("orderId~~ {}",orderId);
                QueryWrapper<Orders> orderWrapper = new QueryWrapper<>();
                orderWrapper.eq("order_id",orderId);
                Orders order = orderMapper.selectOne(orderWrapper);
                if(order != null){
                    Long orderID = order.getId();
                    logger.info("添加合同表~~",orderId);
                    aiDouContractDao.save(orderDetail,orderID);
                    logger.info("添加账单表~~",orderId);
                    aiDouBillDao.save(orderBillList, orderID);
                }else {
                    logger.info("Orders表中未找到订单~~~",orderId);
                }// 手动提交事务
                logger.info("事务提交成功！");
            }
        } catch (Exception e) {
            logger.error("保存数据时发生异常~~~~~~~~~~~~", e);
            throw new RuntimeException(e); // 确保抛出异常以回滚事务
        }
    }
    //对比更新代码
    public void compareUpdate(List<Map<String, Object>> billDtoList, List<OrderBill> existingBill, Long orderID) {
        //System.out.println("billDtoList~~:"+billDtoList);
        //创建一个Map，用于存储数据库中的账单
        Map<Integer, OrderBill> existingBillMap = new HashMap<>();
        for (OrderBill bill : existingBill) {
            existingBillMap.put(bill.getTerm(), bill);
        }
        //logger.info("existingBillMap {}",existingBillMap);
        for (Map<String, Object> billDto : billDtoList) {
            int term = Integer.parseInt(billDto.get("periods").toString()) ;
            String newStatus = "未支付";
            if("PAID".equals(billDto.get("payStatus").toString())){
                newStatus = "已支付";
            }
            else if("OVERDUE_PAID".equals(billDto.get("payStatus").toString())){
                newStatus = "逾期支付";
            }
            OrderBill oldBill = existingBillMap.get(term);
            if (oldBill != null) {
                //对比订单状态
                String oldStatus = oldBill.getRepayStatusStr() != null ? oldBill.getRepayStatusStr() : "";
                Double realPayCapital = 0.0;
                if(billDto.get("actualAmount") != null){
                    realPayCapital = Double.parseDouble(billDto.get("actualAmount").toString());
                }
                if(!newStatus.equals(oldStatus)){
                    //状态不同
                    logger.info("状态不同，第{}期~~", term);
                    UpdateWrapper<OrderBill> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("id", oldBill.getId())
                            .set("real_pay_time", billDto.get("actualTime ")) //支付时间
                            .set("real_pay_capital", realPayCapital)  //还款金额
                            .set("repay_status_str", newStatus) // 还款状态  3 已支付  1 未支付
                            .set("real_repay_time", billDto.get("actualTime"))//还款时间
                            .set("update_time", new Date());
                    orderBillMapper.update(null,updateWrapper);
                }else {
                    //logger.info("状态相同，第{}期~~", term);
                }
            }
        }
    }

    //更新订单数据
    private void updateExistingOrder(Orders existingOrder, Map<String, Object> item,Map<String,Object> orderDetail){
        UpdateWrapper<Orders> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("id", existingOrder.getId());
        //更新订单状态
        int newStatus = getOrderStatus(item.get("orderStatus").toString());
        updateWrapper.set("status", newStatus);
        //更新快递单号
        if(item.get("logisticsNo") != null){
            updateWrapper.set("delivery_no", item.get("logisticsNo"));
        }
        //更新买断价
        Double newBuyoutAmount = Double.parseDouble(orderDetail.get("buyoutTailPrice").toString());
        updateWrapper.set("buyout_amount", newBuyoutAmount);
         //执行更新
        int updated = orderMapper.update(null, updateWrapper);
        logger.info("订单更新完成，更新了 {} 条记录", updated);
    }
    //订单状态映射方法
    public int getOrderStatus(String  status) {
        switch (status) {
            case "TO_BE_RETURNED":
                return 3;
            case "OVERDUE":
                return 4;
            case "COMPLETED":
                return 5;
            case "UNDELIVERED":
                return 1;
            case "TO_BE_RECEIVED":
                return 2;
            default:
                return 7;
        }
    }
}
